<!--
 * @Date: 2024-08-28 14:01:17
 * @Author: LiSong
 * @LastEditors: LiSong
 * @LastEditTime: 2024-10-31 16:52:23
 * @Description: 表格字段导入
-->
<template>
  <vxe-modal :="dialogAttrs" v-model="dialogVisible" @close="handleClose">
    <div class="import-field-body">
      <el-alert style="margin-bottom: 15px;" title="信息提示" type="info" :closable="false">
        <p>录入数据需要为数组形式的JSON数据，数据示例: [ { "field": "name", "title": '名称', "width": 180, "align": "left" } ]</p>
      </el-alert>
      <div class="content-editor-panel">
        <AceCodeEditor mode="text" v-model="codeStore.content"/>
      </div>
    </div>
    <template #footer>
      <el-button size="default" type="primary" @click="handleConfirm">确定</el-button>
      <el-button size="default" @click="handleClose">取消</el-button>
    </template>
  </vxe-modal>
</template>

<script setup name="ParamsDialog">

import { VfMessage } from '@/utils/vf-utils'
import { AceCodeEditor } from '@/components/vf-editor'

import { reactive, ref } from 'vue';
import { baseAttrs } from '@/components/dialogs/cfg/base-cofig.js'


const emits = defineEmits(['close', 'confirm']);

// 弹窗属性
const dialogAttrs = reactive({
  ...baseAttrs,
  title: '字段信息导入',
  width: '55%',
  height: '70%',
  showZoom: false,
  position: { top: 150 },
  showClose: true,
  fullscreen: false,
});
const dialogVisible = ref(false);
const handleOpen = () => {
  dialogVisible.value = true
}
const handleClose = () => {
  dialogVisible.value = false
}
const handleConfirm = () => {
  let content = codeStore.content
  if (!content) {
    VfMessage.warning('请输入需要导入的内容！')
    return
  }
  try {
    content = content ? JSON.parse(content) : [];
    const resCols = parseContent(content)
    emits('confirm', resCols)
    handleClose()
  } catch(error) {
    try {
      content = `return ${content}`
      const execFunc = new Function(content)
      content = execFunc()
      const resCols = parseContent(content)
      emits('confirm', resCols)
      handleClose()
    } catch (ce) {
      const errorMsg = '数据转义出错，请确认参数信息！'
      console.error(errorMsg, error)
      VfMessage.error(errorMsg)
    }
  }
}
const parseContent = (cols) => {
  cols = cols.map(item => {
    return {
      field: item.field,
      title: item.title,
      width: item.width,
      align: item.align || 'left'
    }
  })
  return cols
}
// ----- 表单操作
const codeStore = reactive({
  content: '',
})

defineExpose({
  handleOpen
});
</script>

<style lang="scss" scoped>
.import-field-body {
  display: flex;
  height: 100%;
  flex-direction: column;
  :deep(.el-alert) {
    border: none;
  }
  .content-editor-panel {
    flex: 1;
    min-height: 100px;
  }
}
</style>
